const path = require('path')
const glob = require('glob')
const deployjson = require('./deploy.json')
const fs = require('fs')
//const PrerenderSPAPlugin = require('prerender-spa-plugin')
//const Renderer = PrerenderSPAPlugin.PuppeteerRenderer
const projectNamex = process.argv
const projectName = process.argv[process.argv.length - 1]
// const pages = process.env.NODE_ENV_SD ? setEntry_All() : getEntry(projectName)
const pages = getEntry(projectName,projectNamex)

const Timestamp = new Date().getTime()

let api_url = get_APP_URL(projectName)

process.env.VUE_APP_AOMAIN = get_APP_Aomain() //0测试，1正式

process.env.BASE_URL = `src/projects/${projectName}/assets`; //assets下绝对路径 

process.env.VUE_APP_URL = process.env.NODE_ENV === 'development' ? '' : api_url

process.env.VUE_APP_Version = 1644


module.exports = {
    publicPath: './',
    outputDir: 'dist/' + projectName,
    assetsDir: 'static',
    lintOnSave: false,
    productionSourceMap: false,
    pages: pages,
    devServer: {
        disableHostCheck: true,
        host: '',  // 0.0.0.0
        port: 1644,
        proxy: {
            "": {
                target: api_url,
                ws: true,
                secure: false, // https
                changeOrigin: true, //是否跨域
                //pathRewrite: {'/api':'/'}
            },
            "/foo": {
                target: "<other_url>"
            }
        }
    },
    chainWebpack: (config) => {
        // 移除 prefetch 插件
        config.plugins.delete('prefetch-index') //index.html 禁止利用空闲时间提前获取用户未来可能会访问的内容
        // 移除 preload 插件
        //config.plugins.delete('preload-index'); //用来指定页面加载后很快会被用到的资源，所以在页面加载的过程中，我们希望在浏览器开始主体渲染之前尽早 preload
        config.resolve.alias
            .set('@', resolve('src'))
            .set('_@', resolve(`src/projects/${projectName}`))
            .set('assets', resolve('src/assets'))
            .set('_assets', resolve(`src/projects/${projectName}/assets`))
            .set('components', resolve('src/components'))
            .set('_components', resolve(`src/projects/${projectName}/components`))
            .set('utils', resolve('src/utils'))
            .set('static', resolve('src/static'))
            .set('views', resolve('src/views'))
            .set('_views', resolve(`src/projects/${projectName}/views`))
            .set('_api', resolve(`src/projects/${projectName}/api`));
               
    },
    configureWebpack: (config) => {
        // if (process.env.NODE_ENV === 'production') {
        //     config.mode = 'production'

        //     Object.assign(config, {
        //         output: {
        //             ...config.output,
        //             filename: `static/js/[name].${process.env.VUE_APP_Version}.${Timestamp}.js`,
        //             chunkFilename: `static/js/[name].${process.env.VUE_APP_Version}.${Timestamp}.js`
        //         }
        //     })
        // } else {
        //     config.mode = 'development'
        // }
        // if (process.env.NODE_ENV !== 'production') return;
        // return {
        //     plugins: [
        //         new PrerenderSPAPlugin({
        //             staticDir: path.join(__dirname, `dist/${projectName}`),
        //             routes: ['/', '/about'],
        //             renderer: new Renderer({
        //                 inject: {
        //                     foo: 'bar'
        //                 },
        //                 headless: false,
        //                 renderAfterDocumentEvent: 'render-event'
        //             })
        //         })
        //     ]
        // }
    },
    css: {
        loaderOptions: {
            postcss: {
                plugins: [
                    
                ]
            }
        }
    },
    pluginOptions: { //配置less全局
        'style-resources-loader': {
            preProcessor: 'less',
            patterns: [
                path.resolve(__dirname, `./src/projects/${projectName}/assets/css/mixin.less`)
            ]
        }
    }
}





function resolve (dir) {
    // return path.join(__dirname, './', dir)
    return path.join(__dirname, dir)
}

function getEntry(projectname,projectNamex){
    let entries = {}
    let items = glob.sync( `./src/projects/${projectname}/pubilc/**/*.html`)
    items.forEach(function (filepath) {
        let ext = path.extname(filepath)
        let pageName = path.basename(filepath, ext)
        let pageData = {
            title: '',
            code: pageName
        }
        entries[pageName] = {
            entry: `src/projects/${projectname}/page/${pageName}/main.js`,
            template: `src/projects/${projectname}/pubilc/${pageName}.html`,
            filename: `${pageName}.html`,
            chunks: ['chunk-vendors', 'chunk-common', pageName],               
            title: pageName,
            pageData: pageData,
        }
    })
    return entries
}

function get_APP_Aomain(){ //判断正式还是测试服
    let sd = process.env.NODE_ENV_SD
    let api;
    switch (sd) {
        case 'pre':
            api = 1
            break
        case 'prod':
            api = 1
            break
        default:
            api = 0
            break
    }
    return api
}

function get_APP_URL(projectName){
    let api_url
    let base_info
    deployjson.deploy.forEach((item, index)=> {
        if(item.name === projectName) {
            base_info = item.info
        }
    })
    let sd = process.env.NODE_ENV_SD
    switch (sd) {
        case 'pre':
            api_url = base_info.pre_url
            break
        case 'prod':
            api_url = base_info.prod_url
            break
        default:
            api_url = base_info.dev_url
            break
    }
    return api_url
}

function setEntry_All() {
    let entries = {}
    let path_pro = './src/projects'
    let dirlist = fs.readdirSync(path_pro)
    if( dirlist.length == 0 ){ none } else {
        dirlist.forEach(function(dirname){
            let new_path = path_pro + "/"+ dirname
            if (dirname !== 'admin') {
               Object.assign(entries,getEntry(dirname))
            }
            /* let stat = fs.statSync(new_path);  // 要检查是否为文件夹，需获取stat对象
            if( stat && stat.isDirectory() ){ } */
        });
    } 
}
